package com.liujit.gateway.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.liujit.common.constants.AuthConstant;
import com.liujit.common.constants.HeaderConstant;
import com.liujit.common.enums.ResultCode;
import com.liujit.gateway.constants.GateWayConstant;
import com.liujit.gateway.constants.FilterOrderConstant;
import com.liujit.gateway.security.properties.SecurityProperties;
import com.liujit.gateway.service.RedisService;
import com.liujit.gateway.utils.ResponseUtil;
import com.nimbusds.jose.JWSObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.text.ParseException;
import java.util.List;

/**
 * @Description: 安全拦截全局过滤器
 * @Author: liujun
 * @Date: 2021/6/26 5:50 下午
 */
@RequiredArgsConstructor
@Slf4j
@Component
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityGlobalFilter implements GlobalFilter, Ordered {

    private final RedisService redisService;

    private final SecurityProperties securityProperties;

    @Override
    public int getOrder() {
        return FilterOrderConstant.SECURITY_FILTER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders httpHeaders = request.getHeaders();
        // 当前请求路径
        String currentUrl = request.getPath().pathWithinApplication().value();
        // 判断是否在白名单
        exchange.getAttributes().put(GateWayConstant.IGNORE_URL, false);
        if (this.checkIgnoreUrl(currentUrl)) {
            exchange.getAttributes().put(GateWayConstant.IGNORE_URL, true);
            return chain.filter(exchange);
        }
        String authorization = httpHeaders.getFirst(HeaderConstant.AUTHORIZATION);
        if (StrUtil.isBlank(authorization) || !authorization.startsWith(AuthConstant.BEARER)) {
            return ResponseUtil.writeErrorInfo(response, ResultCode.PERMISSION_NO_ACCESS);
        }
        // 解析JWT获取jti，以jti为key判断redis的黑名单列表是否存在，存在拦截响应token失效
        authorization = authorization.replace(AuthConstant.BEARER, Strings.EMPTY);
        JWSObject jwsObject;
        try {
            jwsObject = JWSObject.parse(authorization);
        } catch (ParseException e) {
            log.error("JWT解析异常：{}", authorization);
            return ResponseUtil.writeErrorInfo(response, ResultCode.PERMISSION_NO_ACCESS);
        }
        String payload = jwsObject.getPayload().toString();
        JSONObject jsonObject = JSONUtil.parseObj(payload);
        String jti = jsonObject.getStr(AuthConstant.JWT_JTI);
        if (StrUtil.isBlank(jti)) {
            log.info("jti为空：{}", payload);
            return ResponseUtil.writeErrorInfo(response, ResultCode.PERMISSION_NO_ACCESS);
        }
        return redisService.exists(jti).flatMap(r -> {
            Boolean res = Convert.toBool(r);
            if (res) {
                return ResponseUtil.writeErrorInfo(response, ResultCode.TOKEN_ACCESS_FORBIDDEN);
            }
            // 存在token且不是黑名单
            // request写入JWT的载体信息，向headers中放文件，记得build
            ServerHttpRequest decorator = exchange.getRequest().mutate().header(HeaderConstant.PAYLOAD, payload)
                    .build();
            // 将现在的request 变成 change对象
            ServerWebExchange mutateExchange = exchange.mutate().request(decorator).build();
            return chain.filter(mutateExchange);
        });
    }

    /**
     * 验证当前url是否在白名单
     *
     * @param currentUrl
     * @return
     * @author: liujun
     * @date: 2021/6/30 9:20 上午
     */
    private Boolean checkIgnoreUrl(String currentUrl) {
        boolean res = false;
        // Ant路径匹配模式
        PathMatcher pathMatcher = new AntPathMatcher();
        List<String> ignoreUrls = securityProperties.getIgnoreUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, currentUrl)) {
                res = true;
                break;
            }
        }
        return res;
    }
}
